import React, { useState } from 'react';
import { Form, Input, Button, Checkbox, message } from 'antd';
import { UserOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { login } from '@/store/slices/authSlice';
import { authApi } from '@/api';
import './Login.scss';

interface LoginForm {
  username: string;
  password: string;
  rememberMe: boolean;
}

const Login: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const dispatch = useDispatch();

  const onFinish = async (values: LoginForm) => {
    setLoading(true);
    try {
      const result = await authApi.login({
        username: values.username,
        password: values.password,
      });

      const { token, userInfo, menus, buttonPermissions = [] } = result;
      
      // 保存token和用户信息
      localStorage.setItem('token', token);
      localStorage.setItem('userInfo', JSON.stringify(userInfo));
      localStorage.setItem('menus', JSON.stringify(menus));
      localStorage.setItem('buttonPermissions', JSON.stringify(buttonPermissions));
      
      // 如果选择记住我，保存用户名
      if (values.rememberMe) {
        localStorage.setItem('rememberedUsername', values.username);
      } else {
        localStorage.removeItem('rememberedUsername');
      }
      // 更新Redux状态
      dispatch(login({ token, userInfo, menus, buttonPermissions }));
      
      message.success('登录成功');
      navigate('/dashboard');
    } catch (error) {
      console.error('登录失败:', error);
      // 错误消息已经在 API 拦截器中处理
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-container">
      <div className="login-form">
        <div className="login-header">
          <h1>后台管理系统</h1>
          <p>欢迎登录</p>
        </div>
        
        <Form
          name="login"
          initialValues={{
            rememberMe: false,
            username: localStorage.getItem('rememberedUsername') || '',
          }}
          onFinish={onFinish}
          size="large"
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="用户名"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password
              prefix={<UserOutlined />}
              placeholder="密码"
            />
          </Form.Item>

          <Form.Item>
            <Form.Item name="rememberMe" valuePropName="checked" noStyle>
              <Checkbox>记住我</Checkbox>
            </Form.Item>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
            >
              登录
            </Button>
          </Form.Item>
        </Form>
        
        <div className="login-footer">
          <p>测试账号: admin / admin123</p>
        </div>
      </div>
    </div>
  );
};

export default Login; 